package cn.iocoder.yudao.module.product.service.property;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.product.api.property.dto.ProductPropertyValueDetailRespDTO;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValuePageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueSaveReqVO;
import cn.iocoder.yudao.module.product.convert.property.ProductPropertyValueConvert;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyDO;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyValueDO;
import cn.iocoder.yudao.module.product.dal.mysql.property.ProductPropertyValueMapper;
import cn.iocoder.yudao.module.product.enums.property.PropertyValueTypeEnum;
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.PROPERTY_VALUE_EXISTS;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.PROPERTY_VALUE_NOT_EXISTS;

/**
 * 商品属性值 Service 实现类
 *
 * @author LuoWenFeng
 */
@Service
@Validated
@Slf4j
public class ProductPropertyValueServiceImpl implements ProductPropertyValueService {

    @Resource
    private ProductPropertyValueMapper productPropertyValueMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private ProductSkuService productSkuService;

    @Resource
    private ProductPropertyService productPropertyService;

    @Override
    public Long createPropertyValue(PropertyValueTypeEnum valueType, ProductPropertyValueSaveReqVO createReqVO) {
        // 如果已经添加过该属性值，直接返回
        ProductPropertyValueDO dbValue = null;
        if (valueType == PropertyValueTypeEnum.SKU){
            // sku上的属性
            dbValue = productPropertyValueMapper.selectByNameAndSkuId(
                    createReqVO.getSkuId(), createReqVO.getPropertyId(), createReqVO.getName());
        }else if (valueType == PropertyValueTypeEnum.SPU){
            // spu上的属性
            dbValue = productPropertyValueMapper.selectByNameAndSpuId(
                    createReqVO.getSpuId(), createReqVO.getPropertyId(), createReqVO.getName());
        }else{
            throw new IllegalArgumentException(String.format("未知的valueType = %s", valueType));
        }

        if (dbValue != null) {
            log.info("属性值-更新, spuId = {}, skuId = {}, propertyId = {}, valueId = {}, displayValue = {}, structuredValue = {}",
                    createReqVO.getSpuId(), createReqVO.getSkuId(), dbValue.getPropertyId(), dbValue.getId(), dbValue.getName(), dbValue.getStructuredValue());

            dbValue.setStructuredValue(createReqVO.getStructuredValue());
            productPropertyValueMapper.updateById(dbValue);
            return dbValue.getId();
        }else{
            // 插入
            createReqVO.setId(null);
            ProductPropertyValueDO value = BeanUtils.toBean(createReqVO, ProductPropertyValueDO.class);
            value.setType(valueType.getValue());
            productPropertyValueMapper.insert(value);
            log.info("属性值-插入, spuId = {}, skuId = {}, propertyId = {}, valueId = {}, displayValue = {}, structuredValue = {}",
                    value.getSpuId(), value.getSkuId(), value.getPropertyId(), value.getId(), value.getName(), value.getStructuredValue());
            return value.getId();
        }
    }

    @Override
    public void updatePropertyValue(ProductPropertyValueSaveReqVO updateReqVO) {
        validatePropertyValueExists(updateReqVO.getId());
        // 校验名字唯一
        ProductPropertyValueDO value = productPropertyValueMapper.selectByName
                (updateReqVO.getPropertyId(), updateReqVO.getName());
        if (value != null && !value.getId().equals(updateReqVO.getId())) {
            throw exception(PROPERTY_VALUE_EXISTS);
        }

        // 更新
        ProductPropertyValueDO updateObj = BeanUtils.toBean(updateReqVO, ProductPropertyValueDO.class);
        productPropertyValueMapper.updateById(updateObj);
        // 更新 sku 相关属性
        //productSkuService.updateSkuPropertyValue(updateObj.getId(), updateObj.getName());
    }

    @Override
    public void deletePropertyValue(Long id) {
        validatePropertyValueExists(id);
        productPropertyValueMapper.deleteById(id);
    }

    private void validatePropertyValueExists(Long id) {
        if (productPropertyValueMapper.selectById(id) == null) {
            throw exception(PROPERTY_VALUE_NOT_EXISTS);
        }
    }

    @Override
    public ProductPropertyValueDO getPropertyValue(Long id) {
        return productPropertyValueMapper.selectById(id);
    }

    @Override
    public List<ProductPropertyValueDO> getPropertyValueListByPropertyId(Collection<Long> propertyIds) {
        return productPropertyValueMapper.selectListByPropertyId(propertyIds);
    }

    @Override
    public Integer getPropertyValueCountByPropertyId(Long propertyId) {
        return productPropertyValueMapper.selectCountByPropertyId(propertyId);
    }

    @Override
    public PageResult<ProductPropertyValueDO> getPropertyValuePage(ProductPropertyValuePageReqVO pageReqVO) {
        return productPropertyValueMapper.selectPage(pageReqVO);
    }

    @Override
    public void deletePropertyValueByPropertyId(Long propertyId) {
        productPropertyValueMapper.deleteByPropertyId(propertyId);
    }

    // ========== 新增 =========

    /**
     * 根据valueId批量删除
     * @param ids
     */
    @Override
    public void deleteBatchIds(Collection<Long> ids){
        productPropertyValueMapper.deleteBatchIds(ids);
    }

    /**
     * 查询spu上的基础属性
     * @param spuIds
     * @return
     */
    @Override
    public List<ProductPropertyValueDO> getPropertyValueListBySpuId(PropertyValueTypeEnum type, Collection<Long> spuIds){
        return productPropertyValueMapper.selectBySpuIds(type, spuIds);
    }

    /**
     * 查询sku上的销售属性
     * @param skuIds
     * @return
     */
    @Override
    public List<ProductPropertyValueDO> getPropertyValueListBySkuId(Collection<Long> skuIds){
        return productPropertyValueMapper.selectBySkuIds(skuIds);
    }

    /**
     * 查询SPU基础属性
     * @param spuId
     * @return
     */
    @Override
    public List<ProductPropertyValueDetailRespDTO> getSpuProperty(PropertyValueTypeEnum type, Long spuId) {
        // 查询属性值
        final List<ProductPropertyValueDO> spuPropertyValueList = getPropertyValueListBySpuId(type, Arrays.asList(spuId));
        if (CollUtil.isEmpty(spuPropertyValueList)){
            return new ArrayList<>();
        }

        return attachPropertyKey(spuPropertyValueList);
    }

    /**
     * 查询SKU销售属性
     * @param skuIds
     * @return
     */
    @Override
    public List<ProductPropertyValueDetailRespDTO> getSkuProperty(Collection<Long> skuIds) {
        // 查询属性值
        final List<ProductPropertyValueDO> skuPropertyValueList = getPropertyValueListBySkuId(skuIds);
        if (CollUtil.isEmpty(skuPropertyValueList)){
            return new ArrayList<>();
        }

        return attachPropertyKey(skuPropertyValueList);
    }

    private List<ProductPropertyValueDetailRespDTO> attachPropertyKey(List<ProductPropertyValueDO> propertyValueDOS) {
        final List<ProductPropertyValueDetailRespDTO> propertyList = new ArrayList<>();
        if (CollUtil.isEmpty(propertyValueDOS)){
            return propertyList;
        }

        // 查询属性值
        final Set<Long> propertyIds = propertyValueDOS.stream().map(v -> v.getPropertyId()).collect(Collectors.toSet());
        final List<ProductPropertyDO> propertyKeyList = productPropertyService.getPropertyList(propertyIds);
        if (CollUtil.isNotEmpty(propertyKeyList)){
            final Map<Long, ProductPropertyDO> propertyId2Data = propertyKeyList.stream().collect(Collectors.toMap(ProductPropertyDO::getId, p -> p));

            for (ProductPropertyValueDO propertyValueDO : propertyValueDOS) {
                final ProductPropertyDO productPropertyDO = propertyId2Data.get(propertyValueDO.getPropertyId());
                if (productPropertyDO != null){
                    final ProductPropertyValueDetailRespDTO property = ProductPropertyValueConvert.convert(propertyValueDO, productPropertyDO.getName());
                    propertyList.add(property);
                }
            }
        }

        return propertyList;
    }

    /**
     * 根据属性名查询属性值
     * @param propertyName
     * @return
     */
    @Override
    public List<ProductPropertyValueDetailRespDTO> getPropertyValueListByPropertyNameGroupByValue(String propertyName) {
        final List<ProductPropertyValueDO> valueDOList = productPropertyValueMapper.selectListByPropertyNameGroupByValue(propertyName);
        final List<ProductPropertyValueDetailRespDTO> list = valueDOList.stream()
                .map(v -> ProductPropertyValueConvert.convert(v, propertyName))
                .collect(Collectors.toList());
        return list;
    }

    /**
     * 根据属性id和属性值查询，并使用propertyValue group by
     * @param type
     * @param propertyId
     * @param propertyValueList
     * @return
     */
    @Override
    public List<ProductPropertyValueDO> selectGroupBySpuId(PropertyValueTypeEnum type, Long propertyId,
                                                           List<String> propertyValueList) {
        return productPropertyValueMapper.selectGroupBySpuId(type, propertyId, propertyValueList);
    }

}
